﻿@model ViewModels.BoardVM.BoardCreateVM

@{
    ViewBag.Title = "Hinoky.com :::: 게시물 수정";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="/Scripts/ckeditor/ckeditor.js" type="text/javascript"></script>
<script src="/Scripts/ckeditor/adapters/jquery.js" type="text/javascript"></script>
<script src="~/Scripts/customJS/board.common.js" type="text/javascript"></script>

<script type="text/javascript">

    $(document).ready(function () {
        CKEDITOR.replace("txtContents", {
            customConfig: "/Scripts/customJS/ckeditor_config.js",
            enterMode: CKEDITOR.ENTER_BR,
            shiftEnterMode: CKEDITOR.ENTER_P,
            width: 840,
        });

        setValidation();

        $("#btnSave").on("click", function() {
            if ($("#form1").valid()) {
                bootbox.confirm("수정하시겠습니까?", function (result) { if (result) saveContent(); });
            }
        });

        var saveContent = function() {
            var idxVal = $("#hidIdx").val();
            var titleVal = htmlEscape($("#txtTitle").val());
            var contentsVal = htmlEscape(CKEDITOR.instances['txtContents'].getData());
            var tagVal = htmlEscape($("#txtTag").val());
            var categories = new Array();
            var isDisplay = $('input[name=rbIsDisplay]:checked').val() == "Y" ? true : false;
            var tempIdx = $("#hidAutoSaveIdx").val();

            $("input[name='txtCategory']").each(function(index, obj) {
                categories.push($(this).val());
            });
            
            $.ajax({
                type: "POST",
                async: true,
                url: "/Board/Edit",
                data: { Idx: idxVal, Title: titleVal, Body: contentsVal, Categories: categories, SearchTag: tagVal, IsDisplay: isDisplay, AutoSaveIdx: tempIdx },
                datatype: 'json',
                traditional: true,
                success: function(data) {
                    if (data.Success == true) {
                        bootbox.alert("수정되었습니다.", function () { location.href = "/Board/Details/" + idxVal; });
                    }
                    else {
                        bootbox.alert("수정에 실패하였습니다.", null);
                    }
                },
                error: function (xhr, status, error) {
                    alert(error);
                }
            });
        }


        var autoSaveDataList = new Array();

        // 임시저장 데이터 보기 클릭시
        $("#btnShowAutoSave").on("click", function () {
            // 임시저장 데이터 로드하기
            $.ajax({
                type: "GET",
                async: true,
                url: "/board/autosavelist",
                datatype: 'json',
                traditional: true,
                success: function (data) {
                    autoSaveDataList = data.AutoSaveList;

                    var html = "";
                    for (var i = 0; i < autoSaveDataList.length; i++) {
                        html += "<label for=\"rboAutoSaveData_" + autoSaveDataList[i].TempIdx + "\"><input type=\"radio\" id=\"rboAutoSaveData_" + autoSaveDataList[i].TempIdx + "\" name=\"rboAutoSaveData\" value=\"" + autoSaveDataList[i].TempIdx + "\" /> " + autoSaveDataList[i].Title + " - [" + autoSaveDataList[i].InsertDate + "]</label><br/>";
                    }
                    $("#divAutoSaveList").html(html);

                    $('#divAutoSavePopup').modal({
                        show: true
                    });
                },
                error: function (xhr, status, error) {
                }
            });
        });

        // 임시저장 기능
        var autoSaveInterval = setInterval(function () {
            var tempIdx = $("#hidAutoSaveIdx").val();
            var titleVal = htmlEscape($("#txtTitle").val());
            var contentsVal = htmlEscape(CKEDITOR.instances['txtContents'].getData());
            var tagVal = htmlEscape($("#txtTag").val());

            if (titleVal == "" && contentsVal == "" && tagVal == "") return;
            $.ajax({
                type: "POST",
                async: true,
                url: "/board/autosave",
                data: { TempIdx: tempIdx, Title: titleVal, Contents: contentsVal, SearchTag: tagVal },
                datatype: 'json',
                traditional: true,
                success: function (data) {
                    if (data.autoSaveIdx > 0) {
                        $("#hidAutoSaveIdx").val(data.autoSaveIdx);
                        console.log("AutoSave Complete");
                    }
                    else {
                        $("hidAutoSaveIdx").val(0);
                        console.log("AutoSave Fail");
                    }
                },
                error: function (xhr, status, error) {
                    clearInterval(autoSaveInterval);
                    console.log("AutoSave Stop");
                }
            });

        }, 10000);

        // 임시저장 리스트에서 아이템 선택시
        $("#btnChoice").on("click", function () {
            var idx = $('input[name=rboAutoSaveData]:checked').val();

            for (var i = 0; i < autoSaveDataList.length; i++) {
                if (autoSaveDataList[i].TempIdx == idx) {
                    $("#txtTitle").val(autoSaveDataList[i].Title);
                    CKEDITOR.instances['txtContents'].insertHtml(htmlUnescape(autoSaveDataList[i].Contents));
                    $("#txtTag").val(autoSaveDataList[i].SearchTag);
                    $("#hidAutoSaveIdx").val(autoSaveDataList[i].TempIdx);

                    break;
                }
            }

            $('#divAutoSavePopup').modal("hide");
        });

    });
</script>

@{
    bool isAdmin = WebLib.AuthorizeService.MemberInfo.Instance.IsSignIn && WebLib.AuthorizeService.MemberInfo.Instance.UserRole.Contains("ADMIN");
}

<h3>게시물 수정</h3>

<p />
<form id="form1">
    <div class="featurebox_center" >
        <input type="hidden" id="hidIdx" name="hidIdx" value="@Model.Idx" />
        <input type="hidden" id="hidAutoSaveIdx" name="hidAutoSaveIdx" value="0" />

        <table class="col-md-12" >
            <tr>
                <td>제목</td>
                <td>
                    <input type="text" class="dashedtb" id="txtTitle" name="txtTitle" value="@Model.Title" />
                    @if (Model.IsExistBoardAutoSave)
                    {
                        <input type="button" id="btnShowAutoSave" value="임시저장데이터 있음" style="background-color: #ff6a00" />
                    }
                </td>
            </tr>
            <tr>
                <td>노출여부</td>
                <td>
                    <label for="rbIsDisplayY"><input type="radio" id="rbIsDisplayY" name="rbIsDisplay" value="Y" @(Model.IsDisplay ? "checked" : "")  />노출</label> &nbsp;
                    <label for="rbIsDisplayY"><input type="radio" id="rbIsDisplayN" name="rbIsDisplay" value="N" @(Model.IsDisplay ? "" : "checked") />비노출</label>
                </td>
            </tr>
            <tr>
                <td>카테고리</td>
                <td>
                    <div style="height:30px" >
                        <div style="float:left" >Category </div>
                        <div id="divCategoryList" style="float:left" >
                            @foreach (var category in Model.Categories)
                            {
                                <input type="text" class="dashedtb_nonewidth" name="txtCategory" value="@category" style="height: 22px" />
                                @:&nbsp;
                            }
                        </div>
                        <a href="#" id="btnAddCate" title="" onclick="return false;"  style="float:left" ><img src="/Images/plus-icon1.png" alt="카테고리 추가" style="width:22px; height:22px;" /></a>
                    </div>
                </td>
            </tr>
            <tr>
                <td>글쓴이</td>
                <td>@Html.Raw(Model.WriteUserName + "(" + Model.WriteUserId + ")")</td>
            </tr>
        </table>
        <br /><br />
        <table class="col-md-12">
            <tr>
                <td><textarea id="txtContents" name="txtContents" >@Model.Body</textarea></td>
            </tr>
            <tr>
                <td>
                    <span class="" >tag명</span>&nbsp; <input type="text" class="dashedtb" id="txtTag" name="txtTag" value="@Model.SearchTag" style="height: 22px" />
                </td>
            </tr>
        </table>

        @if (isAdmin)
        {
            <div class="button_area">
                <span class="button large icon"><span class="check"></span><input type="button" id="btnSave" value="Save"/></span>
            </div>
        }
    </div>
</form>

<!-- (s) 댓글 등록 팝업 (s) -->
<div class="modal fade" id="divAutoSavePopup" tabindex="-1" role="dialog" aria-labelledby="lblAutoSaveTitle" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="lblAutoSaveTitle"><span class="glyphicon glyphicon-plus"></span> 임시저장 리스트</h4>
            </div>

            <div class="modal-body">
                <div class="row" id="divAutoSaveList" >
                    <label for="rboAutoSaveData_1"><input type="radio" id="rboAutoSaveData_1" name="rboAutoSaveData" value="1" /> asdfsdaf dsfasfasdf - [2014-07-15 12:58:01]</label>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" id="btnChoice" class="btn btn-primary"><b>선택</b></button>
                <button type="button" class="btn btn-default" data-dismiss="modal">닫기</button>
            </div>
        </div>
    </div>
</div>